package com.java.simple.study.juc.p5;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhoujunlin
 * @date 2022年11月07日 22:32
 * @desc
 */
@Slf4j(topic = "c.LockCAS")
public class LockCAS {

    /**
     * 0没加锁
     * 1加锁
     */
    private AtomicInteger state = new AtomicInteger(0);

    public void lock() {
        while (true) {
            if (state.compareAndSet(0, 1)) {
                break;
            }
        }
    }

    public void unlock() {
        log.debug("unlock...");
        // 持有锁才会有解锁操作
        state.set(0);
    }

    public static void main(String[] args) {
        LockCAS lockCAS = new LockCAS();
        new Thread(() -> {
            log.debug("begin...");
            lockCAS.lock();
            try {
                log.debug("lock...");
                Sleeper.sleep(1);
            } finally {
                lockCAS.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            log.debug("begin...");
            lockCAS.lock();
            try {
                log.debug("lock...");
            } finally {
                lockCAS.unlock();
            }
        }, "t2").start();
    }


}
